package com.example.ccj.b.a;


import androidx.annotation.ColorRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.example.ccj.R;
import com.example.ccj.b.c.custom.StatusBarHeightView;
import com.example.ccj.b.c.dialog.DialogBase;
import com.example.ccj.b.c.dialog.ErrorDialog;
import com.example.ccj.b.c.dialog.LoadingDialog;
import com.example.ccj.b.c.dialog.TipDialog;
import com.example.ccj.b.c.draw.TopBar;
import com.example.ccj.u.FileUtils;
import com.example.ccj.u.ImageUtils;
import com.example.ccj.u.StatusBarUtil;
import com.example.ccj.u.message.UiMessageUtils;
import com.example.ccj.u.power.PermissionListener;
import com.example.ccj.u.power.PowerPer;


/**
 * activity基类
 * 如果要显示头部，调用 showTopBar 注意必须要在initView之前调用
 * 2024年2月22日11:59:48
 * 驰郡
 * weichar：chijun9
 */
public abstract class BaseActivity extends AppCompatActivity implements IBaseActivity, PermissionListener {
    // 导航栏
    private TopBar topBar;
    public View mContentView;
    public LinearLayout nestedScrollView;
    public StatusBarHeightView statusBarHeightView;
    boolean isCreate = true;//控制数据加载
    int height;
    ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //设置视图
        setContentView(R.layout.activity_base);
        topBar = findViewById(R.id.base_activity_title_bar);

        //获取状态栏高度
        int resourceId = getApplicationContext().getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            height = getApplicationContext().getResources().getDimensionPixelSize(resourceId);
        }
        initContainer();
        //初始化状态栏
        {
            //当FitsSystemWindows设置 true 时，会在屏幕最上方预留出状态栏高度的 padding
            StatusBarUtil.setRootViewFitsSystemWindows(this,false);
            //设置状态栏透明
            StatusBarUtil.setTranslucentStatus(this);
            //一般的手机的状态栏文字和图标都是白色的, 可如果你的应用也是纯白色的, 或导致状态栏文字看不清
            //所以如果你是这种情况,请使用以下代码, 设置状态使用深色文字图标风格, 否则你可以选择性注释掉这个if内容
            if (!StatusBarUtil.setStatusBarDarkTheme(this, true)) {
                //如果不支持设置深色风格 为了兼容总不能让状态栏白白的看不清, 于是设置一个状态栏颜色为半透明,
                //这样半透明+白=灰, 状态栏的文字能看得清
                StatusBarUtil.setStatusBarColor(this,0x55000000);
            }
        }
//        if (isFull()) fullWindow();
//        if (isFullNotReserve()) fullWindowNotReserve();
        imageView = findViewById(R.id.activity_base_loading_img);
        imageView.setVisibility(View.VISIBLE);
        ImageUtils.loadImage(this,R.mipmap.loading_6,imageView);
        isCreate = true;
    }

    protected void fullWindow(){
        StatusBarUtil.setRootViewFitsSystemWindows(this,false);
        statusBarHeightView.setVisibility(View.VISIBLE);
    }

    protected void fullWindowNotReserve(){
        StatusBarUtil.setRootViewFitsSystemWindows(this,false);
    }

    protected boolean isFull(){
        return false;
    }
    protected boolean isFullNotReserve(){
        return false;
    }

    /**
     * 设置状态栏颜色
     * @param color 颜色
     */
    protected void setZhuangTaiLanColor(@ColorRes int color){
        StatusBarUtil.setStatusBarColor(this,color);
    }


    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        if (isCreate) {
            isCreate = false;
            showLoadingDialog();
            handler.sendEmptyMessageDelayed(999,200);
        }
    }

    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            if (msg.what == 999) {
                //初始化顶部
                initTopBar(BaseActivity.this);
                initView(getIntent().getExtras(),mContentView);
                //初始化数据
                initData(getIntent().getExtras());
                doBusiness();
                imageView.setVisibility(View.GONE);
            }
            dismissLoadingDialog();
            return false;
        }
    });

    protected void setTopBarColor(@ColorRes int color){
        topBar.setBackgroundResource(color);
    }

    @Override
    public abstract int initContentView();

    private void initContainer(){
        nestedScrollView = findViewById(R.id.activity_base_scroll_view);
        View view = LayoutInflater.from(this).inflate(initContentView(),null);
//        LogUtils.d("initContainer: ",height);
        if (!isFull()) {
            if (isShowTopBar) topBar.setPadding(0,height,0,0);
            else view.setPadding(0,height,0,0);
        }
        nestedScrollView.addView(view,new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
    }

    boolean isShowTopBar = false;

    /**
     * 顶部导航栏初始化
     */
    private void initTopBar(Activity activity) {

        topBar.setRightHidden();
        topBar.setLeftClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
    }

    public void setTopBarRight(int img,View.OnClickListener onClickListener){
        topBar.setRightIcon(img);
        topBar.setRightClick(onClickListener);
    }

    /**
     * 显示顶部导航栏
     * @param title 名称
     * @return 顶部导航栏可以设置点击事件
     */
    public TopBar showTopBar(String title) {
        isShowTopBar = true;
        topBar.setTitle(title);
        findViewById(R.id.base_activity_title_bar).setVisibility(View.VISIBLE);
        return topBar;
    }

    /**
     * 隐藏软键盘
     */
    public void hideSoftInput() {
        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        if (getCurrentFocus() != null && null != imm) {
            imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
        }
    }

    /**
     * 显示软键盘
     */
    public void showSoftInput() {
        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        if (getCurrentFocus() != null && null != imm) {
            imm.showSoftInputFromInputMethod(getCurrentFocus().getWindowToken(), 0);
        }
    }

    /**
     * 设置屏幕横竖屏切换
     *
     * @param screenRoate true  竖屏     false  横屏
     */
    @SuppressWarnings("all")
    public void setScreenRoate(Boolean screenRoate) {
        if (screenRoate) {
            //设置竖屏模式
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        } else {
            //设置横屏模式
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }
    }


    /**
     * *******************************************************
     * 加载等待
     * *******************************************************
     */
    LoadingDialog loadingDialog;
    /**
     * 显示加载等待
     */
    public void showLoadingDialog(){
        if (loadingDialog == null) loadingDialog = new LoadingDialog(this);
        loadingDialog.showLoading();
    }

    /**
     * 显示圆圈进度等待
     * @param max 进度最大值
     */
    public void showUpdateLoadingDialog(int max){
        if (loadingDialog == null) loadingDialog = new LoadingDialog(this);
        loadingDialog.showUpload(max);
    }

    /**
     * 设置圆圈进度值
     */
    @SuppressWarnings("all")
    public void setUpdateLoadingSpeed(int speed){
        if (loadingDialog != null && loadingDialog.isShowing()) loadingDialog.setSpeed(speed);
    }

    /**
     * 设置圆圈进度文本
     * @param str 进度文本
     */
    @SuppressWarnings("all")
    public void setUpdateLoadingText(String str){
        if (loadingDialog != null && loadingDialog.isShowing()) loadingDialog.setUploadText(str);
    }

    /**
     * 关闭加载或者更新进度界面
     */
    @SuppressWarnings("all")
    public void dismissLoadingDialog(){
        if (loadingDialog != null && loadingDialog.isShowing()) loadingDialog.dismiss();
    }

    DialogBase dialogBase;
    @SuppressWarnings("all")
    public void showTipDialog(String value){
        dialogBase = new TipDialog(this,value);
        dialogBase.show();
    }

    @SuppressWarnings("all")
    public void showErrorDialog(String value){
        dialogBase = new ErrorDialog(this,value);
        dialogBase.show();
    }
    /**
     * 跳转页面
     *
     * @param clz 所跳转的目的Activity类
     */
    public void jump(Class<?> clz){
        startActivity(new Intent(this, clz));
    }
    /**
     * 跳转页面
     *
     * @param clz    所跳转的目的Activity类
     * @param bundle 跳转所携带的信息
     */
    public void jump(Class<?> clz, Bundle bundle){
        Intent intent = new Intent(this, clz);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivity(intent);
    }

    public void getLocationPermissions(){
        PowerPer.getMultiPermission(this,259,new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION,
                android.Manifest.permission.ACCESS_FINE_LOCATION});
    }

    //重写该方法根据返回码确定要执行那个操作
    @Override
    public void onPermissionGranted(int requestCode) {

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PowerPer.requestMultiResult(this,requestCode,permissions,grantResults,this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == FileUtils.PICK_FILE_RESULT && data != null) {
            UiMessageUtils.getInstance().send(FileUtils.PICK_FILE_RESULT,data);
        }
        if (requestCode == LocationMapActivity.RESULT_LOCATION_CODE && data != null) {
            UiMessageUtils.getInstance().send(LocationMapActivity.RESULT_LOCATION_CODE,data);
        }
    }
}
